<template>
  <div class="household-edit-container">
    <el-card class="household-edit-card">
      <template #header>
        <div class="card-header">
          <span>编辑房户</span>
          <div class="header-buttons">
            <el-button @click="handleBack">
              <el-icon><ArrowLeft /></el-icon>
              返回列表
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 房户信息表单 -->
      <div class="form-area" v-if="!loading">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房户编号" prop="householdCode">
                <el-input
                  v-model="formData.householdCode"
                  placeholder="请输入房户编号"
                  maxlength="50"
                  show-word-limit
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间号" prop="roomNumber">
                <el-input
                  v-model="formData.roomNumber"
                  placeholder="请输入房间号"
                  maxlength="10"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属社区" prop="communityName">
                <el-input v-model="formData.communityName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属楼栋" prop="buildingName">
                <el-input v-model="formData.buildingName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属单元" prop="unitName">
                <el-input v-model="formData.unitName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="楼层号" prop="floorNumber">
                <el-input-number
                  v-model="formData.floorNumber"
                  :min="1"
                  :max="100"
                  placeholder="请输入楼层号"
                  style="width: 100%"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房屋面积" prop="area">
                <el-input-number
                  v-model="formData.area"
                  :min="1"
                  :max="1000"
                  :precision="2"
                  placeholder="请输入房屋面积"
                  style="width: 100%"
                />
                <span class="unit-text">平方米</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用面积" prop="usableArea">
                <el-input-number
                  v-model="formData.usableArea"
                  :min="1"
                  :max="1000"
                  :precision="2"
                  placeholder="请输入使用面积"
                  style="width: 100%"
                />
                <span class="unit-text">平方米</span>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="朝向" prop="orientation">
                <el-select
                  v-model="formData.orientation"
                  placeholder="请选择朝向"
                  style="width: 100%"
                >
                  <el-option label="东" value="东" />
                  <el-option label="南" value="南" />
                  <el-option label="西" value="西" />
                  <el-option label="北" value="北" />
                  <el-option label="东南" value="东南" />
                  <el-option label="西南" value="西南" />
                  <el-option label="东北" value="东北" />
                  <el-option label="西北" value="西北" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间类型" prop="roomType">
                <el-select
                  v-model="formData.roomType"
                  placeholder="请选择房间类型"
                  style="width: 100%"
                >
                  <el-option label="一室" :value="1" />
                  <el-option label="两室" :value="2" />
                  <el-option label="三室" :value="3" />
                  <el-option label="四室及以上" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产权类型" prop="propertyType">
                <el-select
                  v-model="formData.propertyType"
                  placeholder="请选择产权类型"
                  style="width: 100%"
                >
                  <el-option label="自有" :value="1" />
                  <el-option label="租赁" :value="2" />
                  <el-option label="其他" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房产证号" prop="propertyCertificate">
                <el-input
                  v-model="formData.propertyCertificate"
                  placeholder="请输入房产证号"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="购买日期" prop="purchaseDate">
                <el-date-picker
                  v-model="formData.purchaseDate"
                  type="date"
                  placeholder="请选择购买日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物业费单价" prop="propertyFeeRate">
                <el-input-number
                  v-model="formData.propertyFeeRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  placeholder="请输入物业费单价"
                  style="width: 100%"
                />
                <span class="unit-text">元/平方米</span>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房户状态" prop="status">
                <el-select
                  v-model="formData.status"
                  placeholder="请选择房户状态"
                  style="width: 100%"
                >
                  <el-option label="空置" :value="0" />
                  <el-option label="已入住" :value="1" />
                  <el-option label="装修中" :value="2" />
                  <el-option label="出租" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="装修状态" prop="decorationStatus">
                <el-select
                  v-model="formData.decorationStatus"
                  placeholder="请选择装修状态"
                  style="width: 100%"
                >
                  <el-option label="毛坯" :value="0" />
                  <el-option label="简装" :value="1" />
                  <el-option label="精装" :value="2" />
                  <el-option label="豪装" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="房户描述" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  placeholder="请输入房户描述"
                  :rows="3"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        
        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="handleBack">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            保存修改
          </el-button>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div class="loading-area" v-if="loading">
        <el-skeleton :rows="10" animated />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
/**
 * 房户编辑页面
 * @author Wu.Liang
 * @date 2025-01-30
 */
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { householdApi } from '@/api/household'
import { householdFormRules } from '@/types/region'

// 初始化router和route
const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const formRef = ref()

// 表单数据
const formData = reactive({
  id: undefined as number | undefined,
  householdCode: '',
  roomNumber: '',
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  communityName: '',
  buildingName: '',
  unitName: '',
  floorNumber: 1,
  area: 0,
  usableArea: 0,
  orientation: '',
  roomType: 1,
  propertyType: 1,
  propertyCertificate: '',
  purchaseDate: '',
  propertyFeeRate: 0,
  status: 0,
  decorationStatus: 0,
  description: ''
})

// 表单验证规则 - 编辑页面专用，移除不可编辑字段的验证
const formRules = {
  roomNumber: [
    { required: true, message: '请输入房间号', trigger: 'blur' },
    { max: 20, message: '房间号长度不能超过20个字符', trigger: 'blur' }
  ],
  roomType: [
    { required: true, message: '请选择房间类型', trigger: 'change' }
  ],
  area: [
    { type: 'number', min: 0, max: 1000, message: '房屋面积必须在0-1000平方米之间', trigger: 'blur' }
  ],
  usableArea: [
    { type: 'number', min: 0, max: 1000, message: '使用面积必须在0-1000平方米之间', trigger: 'blur' }
  ],
  propertyType: [
    { required: true, message: '请选择产权类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择房户状态', trigger: 'change' }
  ]
}

// 获取房户ID
const getHouseholdId = () => {
  const id = route.params.id
  return id ? Number(id) : undefined
}

// 加载房户详情
const loadHouseholdDetail = async () => {
  const householdId = getHouseholdId()
  if (!householdId) {
    ElMessage.error('房户ID无效')
    handleBack()
    return
  }
  
  try {
    loading.value = true
    const response = await householdApi.getHouseholdDetail(householdId)
    if (response.data) {
      // 确保数字字段的类型正确
      const processedData = {
        ...response.data,
        id: response.data.id != null ? Number(response.data.id) : undefined,
        communityId: response.data.communityId != null ? Number(response.data.communityId) : undefined,
        buildingId: response.data.buildingId != null ? Number(response.data.buildingId) : undefined,
        unitId: response.data.unitId != null ? Number(response.data.unitId) : undefined,
        floorNumber: response.data.floorNumber != null ? Number(response.data.floorNumber) : 1,
        area: response.data.area != null ? Number(response.data.area) : 0,
        usableArea: response.data.usableArea != null ? Number(response.data.usableArea) : 0,
        roomType: response.data.roomType != null ? Number(response.data.roomType) : 1,
        propertyType: response.data.propertyType != null ? Number(response.data.propertyType) : 1,
        propertyFeeRate: response.data.propertyFeeRate != null ? Number(response.data.propertyFeeRate) : 0,
        status: response.data.status != null ? Number(response.data.status) : 0,
        decorationStatus: response.data.decorationStatus != null ? Number(response.data.decorationStatus) : 0
      }
      Object.assign(formData, processedData)
    } else {
      ElMessage.error('获取房户详情失败')
      handleBack()
    }
  } catch (error) {
    console.error('获取房户详情失败:', error)
    ElMessage.error('获取房户详情失败')
    handleBack()
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    submitting.value = true
    
    // 只传递可编辑的字段，避免传递不可编辑的字段
    const updateData = {
      id: formData.id,
      roomNumber: formData.roomNumber,
      area: formData.area,
      usableArea: formData.usableArea,
      orientation: formData.orientation,
      roomType: formData.roomType,
      propertyType: formData.propertyType,
      propertyCertificate: formData.propertyCertificate,
      purchaseDate: formData.purchaseDate,
      propertyFeeRate: formData.propertyFeeRate,
      status: formData.status,
      decorationStatus: formData.decorationStatus,
      description: formData.description
    }
    
    await householdApi.updateHouseholdOptimized(formData.id!, updateData)
    
    ElMessage.success('更新成功')
    handleBack()
  } catch (error) {
    if (error !== false) {
      ElMessage.error('更新失败')
    }
  } finally {
    submitting.value = false
  }
}

// 返回列表
const handleBack = () => {
  router.push('/region/household')
}

// 组件挂载时初始化
onMounted(() => {
  loadHouseholdDetail()
})
</script>

<style lang="scss" scoped>
.household-edit-container {
  padding: 20px;
  
  .household-edit-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-buttons {
        display: flex;
        gap: 10px;
      }
    }
    
    .form-area {
      .form-actions {
        margin-top: 30px;
        text-align: center;
        
        .el-button {
          margin: 0 10px;
        }
      }
    }
    
    .loading-area {
      padding: 20px;
    }
  }
}

.unit-text {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}
</style>
